﻿using System;
using System.Text.RegularExpressions;
using TidyBlog.Entity;
using TidyBlog.BLL;
using System.Web;
using System.Web.Mvc;

namespace TidyBlog.MVC
{
    /// <summary>
    /// 定义前台页面每个动作前后的公共操作
    /// </summary>
    public class FrontActionFilter : BaseActionFilter
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);

            dynamic viewBag = filterContext.Controller.ViewBag;
            // 读取可见分类
            viewBag.CategoryList = CategoryBLL.List(1);

            var controllerName = filterContext.RouteData.Values["controller"].ToString();
            // 检查站点是否已关闭
            // TODO 登录页访问限制重构
            if (CurrentSetup.IsOpen == 0 && controllerName != "Info" && controllerName != "User")
            {
                throw new Exception(CurrentSetup.CloseReason);
            }

            // 检查是否黑名单IP
            if (!String.IsNullOrEmpty(CurrentSetup.ForbiddenIP))
            {
                var userIP = filterContext.HttpContext.Request.GetClientIP();
                foreach (var ip in Regex.Split(CurrentSetup.ForbiddenIP, @"[\r\n]+"))
                {
                    if (ip == userIP)
                    {
                        throw new Exception("您使用的IP已被禁止访问");
                    }
                }
            }

            // 读取可见链接
            viewBag.LinkList = LinkBLL.List(1);
        }
    }
}
